/*
Copyright (C) 2022-2024 Inspur Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package upload

import (
	"icep/common/logger"
	"icep/common/utils"
	"icep/config"

	"github.com/minio/minio-go"
)

var log = logger.GetLogger("common.upload")

type MinioConfig struct {
	Endpoint    string `json:"endpoint"`
	AccessKeyId string `json:"accessKeyId"`
	AccessKey   string `json:"accessKey"`
	BucketName  string `json:"bucketName"`
	UseSsl      bool   `json:"useSsl"`
	AgentUrl    string `json:"agentUrl"`
}

type MinioClient struct {
	Config *MinioConfig
	Client *minio.Client
}

func loadConfig() *MinioConfig {
	minioConfig := &MinioConfig{}
	minioConfig.Endpoint = config.Get("icep.upload.minio.endpoint", "localhost:9000")
	minioConfig.AccessKeyId = config.Get("icep.upload.minio.access-key-id", "minioadmin")
	minioConfig.AccessKey = config.Get("icep.upload.minio.access-key", "minioadmin")
	minioConfig.BucketName = config.Get("icep.upload.minio.bucket-name", "icep")
	minioConfig.UseSsl = config.GetBool("icep.upload.minio.use-ssl")
	minioConfig.AgentUrl = config.Get("icep.upload.minio.agent-url", "")
	return minioConfig
}

func GetUploadClient() *MinioClient {
	minioConfig := loadConfig()
	client, err := minio.New(minioConfig.Endpoint, minioConfig.AccessKeyId,
		minioConfig.AccessKey, minioConfig.UseSsl)
	if err != nil {
		log.Errorf("get upload client error: %s", err)
		return nil
	}
	return &MinioClient{
		Config: minioConfig,
		Client: client,
	}
}

func (mc *MinioClient) UploadFile(filePath, uploadPath string) (string, error) {
	_, err := mc.Client.FPutObject(mc.Config.BucketName, uploadPath, filePath, minio.PutObjectOptions{
		ContentType: "",
	})
	if err != nil {
		log.Errorf("upload file error: %s", err)
		return "", err
	}
	schem := "http://"
	if mc.Config.UseSsl {
		schem = "https://"
	}
	url := utils.StrJoin(schem, mc.Config.Endpoint, "/", mc.Config.BucketName, "/", uploadPath)
	if mc.Config.AgentUrl != "" {
		url = utils.StrJoin(mc.Config.AgentUrl, "/", mc.Config.BucketName, "/", uploadPath)
	}

	return url, nil
}
